//
//  HttpRequest.m
//  基于AFNetWorking的再封装
//
//  Created by fengXC on 16/5/26.
//  Copyright © 2016年 TrendyFeng. All rights reserved.
//

#import "HttpRequest.h"
#import "AFNetworking.h"
#import "KDLoadFrame.h"
#import "Header.h"
#import "YLLoginViewController.h"
#import "YLNavigationViewController.h"
#import "YLHttpModel.h"

@implementation UploadParam
@end

@implementation HttpRequest

static id _instance = nil;
+ (instancetype)sharedInstance {
    return [[self alloc] init];
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [super allocWithZone:zone];
    });
    return _instance;
}

- (instancetype)init {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [super init];
        AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
        [manager startMonitoring];
        [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
            switch (status) {
                case AFNetworkReachabilityStatusUnknown:
                {
                    // 位置网络
                    NSLog(@"位置网络");
                }
                    break;
                case AFNetworkReachabilityStatusNotReachable:
                {
                    // 无法联网
                    NSLog(@"无法联网");
                    
                    
                }
                    break;
                case AFNetworkReachabilityStatusReachableViaWiFi:
                {
                    // 手机自带网络
                    NSLog(@"当前使用的是2G/3G/4G网络");
                }
                    break;
                case AFNetworkReachabilityStatusReachableViaWWAN:
                {
                    // WIFI
                    NSLog(@"当前在WIFI网络下");
                }
            }
        }];
    });
    return _instance;
}

#pragma mark -- GET请求 --
+ (void)getWithURLString:(NSString *)URLString
              parameters:(id)parameters
                 success:(void (^)(id))success
                 failure:(void (^)(NSError *))failure {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    /**
     *  可以接受的类型
     */
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    /**
     *  请求队列的最大并发数
     */
//    manager.operationQueue.maxConcurrentOperationCount = 5;
    /**
     *  请求超时的时间
     */
//    manager.requestSerializer.timeoutInterval = 30;
    [manager GET:URLString parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            id dataObject = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            responseObject = dataObject;
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
    }];
    
    
}

#pragma mark -- POST请求 --
+ (void)postWithURLString:(NSString *)URLString
               parameters:(id)parameters
                  success:(void (^)(id))success
                  failure:(void (^)(NSError *))failure {
    NSString *newUrl = URLString;
    NSDictionary *dict = parameters;
    NSString *tmpTxt = @"";
    printf("\n|-----------------------------------------------");
    for ( NSString *tmpKey in dict.allKeys ) {
        
        NSString *value = [NSString stringWithFormat:@"%@",[dict objectForKey:tmpKey]];
        tmpTxt = [tmpTxt stringByAppendingFormat:@"%@=%@&",tmpKey,[dict objectForKey:tmpKey]];
        printf("\n| %s = %s ",[tmpKey UTF8String],[value UTF8String]);
    }
    printf("\n|-----------------------------------------------");
    printf("\n| url = %s",[newUrl UTF8String]);
    printf("\n| url + body = %s?%s",[newUrl UTF8String],[tmpTxt UTF8String]);
    printf("\n|-----------------------------------------------");
    newUrl = [newUrl stringByAppendingFormat:@"?%@",tmpTxt];
    
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 120;
    
    [manager POST:newUrl parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
    }];
}

#pragma mark -- POST/GET网络请求 --
+ (void)requestWithURLString:(NSString *)URLString
                  parameters:(id)parameters
                        type:(HttpRequestType)type
                     success:(void (^)(id))success
                     failure:(void (^)(NSError *))failure {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    AFJSONResponseSerializer *response = [AFJSONResponseSerializer serializer];
    response.removesKeysWithNullValues = YES;
    manager.requestSerializer.timeoutInterval = 120;
    NSMutableCharacterSet * allowedCharacterSet = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy];
    URLString = [URLString stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet];
    /*==================*/
    
    switch (type) {
        case HttpRequestTypeGet:
        {
            [manager GET:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                if (success) {
                    
                    id dataObject = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
                    responseObject = dataObject;
                    printf("\n|---------------HttpRequestTypeGet---------------");
                    printf("\n| url = %s",[URLString UTF8String]);
                    printf("\n| response = %s",[[NSString stringWithFormat:@"%@",responseObject] UTF8String]);
                    printf("\n|-----------------------------------------------\n\n");
                    success(responseObject);
                }
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                if (failure) {
                    failure(error);
                    [KDLoadFrame withState:KDLoadStateHide];
                    NSString *errMsg = [error localizedDescription];

                    printf("\n|---------------HttpRequestTypeGet---------------");
                    printf("\n| url = %s",[URLString UTF8String]);
                    printf("\n| errMsg = %s",[errMsg UTF8String]);
                    printf("\n|-----------------------------------------------\n\n");
                }
            }];
        }
            break;
        case HttpRequestTypePost:
        {
            
            [manager POST:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                if (success) {

                    id dataObject = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
                    responseObject = dataObject;
                    YLHttpModel *httpModel = [YLHttpModel yy_modelWithDictionary:responseObject];
                    if([httpModel.status isEqualToString:@"405"]){
                    
                        UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"温馨提示"  message:@"您的账号在其他设备登录，请重新登录" preferredStyle:UIAlertControllerStyleAlert];
                        
                        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                            YLLoginViewController *loginVC = [[YLLoginViewController alloc] initWithNibName:@"YLLoginViewController" bundle:nil];
                            YLNavigationViewController *loginNav = [[YLNavigationViewController alloc] initWithRootViewController:loginVC];
                            [UIApplication sharedApplication].keyWindow.rootViewController = loginNav;
                            
                        }];
                        [alert addAction:cancelAction];
                        
                        UIViewController * rootViewController = [[[UIApplication sharedApplication] keyWindow] rootViewController];
                        [rootViewController presentViewController:alert animated:YES completion:nil];
                        
                       
                    }else{
                      success(responseObject);
                    }
                    
                    
                    printf("\n|--------------HttpRequestTypePost--------------");
                    printf("\n| url = %s",[URLString UTF8String]);
                    printf("\n| response = %s",[[NSString stringWithFormat:@"%@",responseObject] UTF8String]);
                    printf("\n|-----------------------------------------------\n\n");
                    AFJSONResponseSerializer *response = [AFJSONResponseSerializer serializer];
                    response.removesKeysWithNullValues = YES;
                    manager.requestSerializer.timeoutInterval = 120;
                    
                }
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                if (failure) {
                    failure(error);
                    [KDLoadFrame withState:KDLoadStateHide];
                    printf("\n|--------------HttpRequestTypePost--------------");
                    printf("\n| url = %s",[URLString UTF8String]);
                    NSString *errMsg = [error localizedDescription];
                    printf("\n| errMsg = %s",[errMsg UTF8String]);
                    printf("\n|-----------------------------------------------\n\n");
                }
            }];
        }
            break;
    }
}

#pragma mark -- 上传图片 --
+ (void)uploadWithURLString:(NSString *)URLString
                 parameters:(id)parameters
                uploadParam:(UploadParam *)uploadParam
                    success:(void (^)(id responseObject))success
                    failure:(void (^)(NSError *))failure {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 300;
    
    //公共参数
    /*==================*/

    
    [manager POST:URLString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:uploadParam.data name:uploadParam.name fileName:uploadParam.filename mimeType:uploadParam.mimeType];
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            
            printf("\n|----------------HttpRequestImage---------------");
            printf("\n| url = %s",[URLString UTF8String]);
            printf("\n| response = %s",[[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding] UTF8String]);
            printf("\n|-----------------------------------------------");
            
            id dataObject = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            responseObject = dataObject;
            YLHttpModel *httpModel = [YLHttpModel yy_modelWithDictionary:responseObject];
            if([httpModel.status isEqualToString:@"405"]){
                UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"温馨提示"  message:@"您的账号在其他设备登录，请重新登录" preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                    YLLoginViewController *loginVC = [[YLLoginViewController alloc] initWithNibName:@"YLLoginViewController" bundle:nil];
                    YLNavigationViewController *loginNav = [[YLNavigationViewController alloc] initWithRootViewController:loginVC];
                    [UIApplication sharedApplication].keyWindow.rootViewController = loginNav;
                    
                }];
                [alert addAction:cancelAction];
                
                UIViewController * rootViewController = [[[UIApplication sharedApplication] keyWindow] rootViewController];
                [rootViewController presentViewController:alert animated:YES completion:nil];
            }else{
                success(responseObject);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
            printf("\n|----------------HttpRequestImage---------------");
            printf("\n| url = %s",[URLString UTF8String]);
            NSString *errMsg = [error localizedDescription];
            printf("\n| errMsg = %s",[errMsg UTF8String]);
            printf("\n|-----------------------------------------------\n\n");
        }
    }];
}


+ (void)uploadWithURLString:(NSString *)URLString
                 parameters:(id)parameters
                uploadParamAr:(NSArray <UploadParam *> *)uploadParamAr
                    success:(void (^)(id responseObject))success
                    failure:(void (^)(NSError *))failure {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 300;
    /*==================*/
    
    
    [manager POST:URLString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        for (UploadParam *uploadParam in uploadParamAr) {
            [formData appendPartWithFileData:uploadParam.data name:uploadParam.name fileName:uploadParam.filename mimeType:uploadParam.mimeType];
        }
        
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            
            printf("\n|----------------HttpRequestImage---------------");
            printf("\n| url = %s",[URLString UTF8String]);
            printf("\n| response = %s",[[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding] UTF8String]);
            printf("\n|-----------------------------------------------");
            
            id dataObject = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            responseObject = dataObject;
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
            printf("\n|----------------HttpRequestImage---------------");
            printf("\n| url = %s",[URLString UTF8String]);
            NSString *errMsg = [error localizedDescription];
            printf("\n| errMsg = %s",[errMsg UTF8String]);
            printf("\n|-----------------------------------------------\n\n");
        }
    }];
}

+ (void)multipartFormPath:(NSString *)URLString  parameters:(id)parameters  fileSource:(NSArray *)fileSource   success:(void (^)(id responseObject))success   failure:(void (^)(NSError *error))failure{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 300;
    
    [manager POST:URLString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        for(int i=0; i<fileSource.count; i++){
        
            NSData *fileData =[[fileSource objectAtIndex:i] valueForKey:kFILEDATA];
            
            NSString *name = [[fileSource objectAtIndex:i] valueForKey:kNAME];
            
            NSString *filePath = [[fileSource objectAtIndex:i] valueForKey:kFILEPATH];
            
            
            if (fileData != NULL) {
                
                [formData appendPartWithFileData:fileData name:name fileName:filePath mimeType:kImageType];
            }
        }
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
    }];
}


+(void)uploadTextWithUrlString:(NSString *)urlString parameters:(id)parameters withTxtPath:(NSString *)txtPath withTxtName:(NSString *)txtName success:(void (^)(id))success failure:(void (^)(NSError *))failure{
    
    
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 300;
    
    [manager POST:urlString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        NSData *txtData = [NSData dataWithContentsOfFile:txtPath];
        /*! 拼接data */
        if (txtData != nil)
        {
            [formData appendPartWithFileData:txtData
                                        name:txtName
                                    fileName:txtName
                                    mimeType:@"txt"];
        }
        
        
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            success(responseObject);
            
            
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
    }];
    
    
    
}



@end
